import React = require("react");
import { PageProps } from "maishu-chitu-react";
import { defaultPageDatas, findChildComponentData } from "services/page-datas";
import { DesignView } from "controls/design-view";
import { LocalService } from "services/local-service";
import { ShoppingService } from "services/shopping";
import { ProductInfo, Props as ProductInfoProps } from "components/product-info/component";
import { dataSources } from "services/dataSources";
import { PageDataRecord } from "entities";

interface Props extends PageProps {
    data: {
        id: string
    }
}

interface State {
    pageDataRecord: PageDataRecord
}

export default class ProductPage extends React.Component<Props, State> {
    localService: LocalService;
    shoppingService: ShoppingService;
    designView: DesignView;

    constructor(props: Props) {
        super(props);

        this.state = { pageDataRecord: { pageData: defaultPageDatas.empty() } as PageDataRecord };
        this.localService = this.props.createService(LocalService);
        this.shoppingService = this.props.createService(ShoppingService);
    }
    async componentDidMount() {
        let pageDataRecord = await this.localService.getPageDataRecordById(this.props.data.id);
        console.assert(pageDataRecord != null);
        this.setState({ pageDataRecord });
        let designViewSave = this.designView.save;
        this.designView.save = async () => {

            let productInfoData = findChildComponentData(pageDataRecord, ProductInfo.name);
            let product = (productInfoData.props as ProductInfoProps).product;
            await dataSources.product.update(product);
            return designViewSave.apply(this);
        }
    }
    render() {
        let { pageDataRecord: pageData } = this.state;

        return <DesignView {...{ app: this.props.app, }} pageDataRecord={pageData}
            hidePageSettingPanel={true}
            ref={e => this.designView = this.designView || e}>

        </DesignView>
    }
}